#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
	int z, mlen;
	int s[2];
	pid_t chpid;
	char *msgp, buf[80];

	/* Create pair of local sockets					*/
	z = socketpair(AF_LOCAL, SOCK_STREAM, 0, s);
	if(z == -1) {
		fprintf(stderr,"%s: socketpair(AF_LOCAL, SOCK_STREAM, 0)\n", strerror(errno));
	}

	/* Fork a two processes						*/
	if((chpid = fork()) == (pid_t) -1) {
		/* Failed to fork processes				*/
		fprintf(stderr,"%s: fork()\n", strerror(errno));
		exit(1);
	} else if(chpid == 0) {
		/* This is child process				*/
		char rxbuf[80];
		printf("Parent PID is %ld\n", (long) getppid());
		close(s[0]);		/* server uses s[1]		*/
		s[0] = -1;		/* Forget this unit		*/

		msgp =  "%A %d-%b-%Y %l:%M %p";
		mlen = strlen(msgp);

		printf("Child sending request '%s'\n", msgp);
		fflush(stdout);

		/* Write request to the server				*/
		z = write(s[1], msgp, mlen);
		if(z < 0) {
			fprintf(stderr,"%s: write(%d, \"%s\", %d)\n", strerror(errno), s[1], msgp, mlen);
			exit(1);
		}
		/* receive the reply from the server			*/
		z = read(s[1], rxbuf, sizeof(rxbuf));
		if(z < 0) {
			fprintf(stderr, "%s: read(%d, rxbuf, %d)\n", strerror(errno), s[1], sizeof(rxbuf));
			exit(1);
		}
		rxbuf[z] = 0;

		/* Report the result					*/
		printf("Server returned %s\n", rxbuf);
		fflush(stdout);
	} else {
		/* This is parent process				*/
		int status;
		char txbuf[80];
		time_t td;	

		printf("Child PID is %ld\n", (long) chpid);
		fflush(stdout);

		close(s[1]);		/* Client uses s[1]		*/
		s[1] = -1;		/* Forget this unit		*/

		/* Wait for the request from the cluent			*/
		z = read(s[0], buf, sizeof(buf));
		if(z < 0) {
			fprintf(stderr,"%s: read(%d, buf, %d)\n", strerror(errno), s[0], sizeof(buf));
			exit(1);
		}
		buf[z] = 0;

		/* Perform server function on received message		*/
		time(&td);
		strftime(txbuf, sizeof(txbuf), buf, localtime(&td));

		/* Send back the responce to the client			*/
		z = write(s[0], txbuf, strlen(txbuf));
		if(z < 0) {
			fprintf(stderr,"%s: write(%d, \"%s\", %d)\n", strerror(errno), s[0], txbuf, strlen(txbuf));
			exit(1);
		}

		close(s[0]);
		waitpid(chpid, &status, 0);
	}

	return(0);
}
